/*
 *  Copyright (c) 2024 Cshoo Org. All Rights Reserved.
 *
 *  author:杨翼
 *  date: 2024年4月29日
 *  description:album组件客户端js,负责3d轮播图的交互
 */

(function () {
    const items = document.querySelectorAll('.carousel-item');
    let index = Math.floor(items.length / 2);// 当前显示的图片索引

    const offsetStep = document.querySelector('#offsetStep').value;// 每两张图片之间的偏移量
    const baseOffset = document.querySelector('#baseOffset').value;// 左右两张离中间图片的基础偏移量
    const scaleStep = document.querySelector('#scaleStep').value;// 每两张图片之间的缩放比例差
    const opacityStep = document.querySelector('#opacityStep').value;// 每两张图片之间的透明度差
    const rotateX = document.querySelector('#rotateX').value;// 每张图片沿X轴旋转的绝度
    const rotateY = document.querySelector('#rotateY').value;// 每张图片沿Y轴旋转的角度

    function layout() {
        for (let i = 0; i < items.length; i++) {
            let dis = Math.abs(i - index);
            let sign = Math.sign(i - index);
            const item = items[i];
            // transform
            // translateX
            let xOffset = (i - index) * offsetStep;
            if (i !== index) {
                xOffset = xOffset + baseOffset * sign;
            }

            // scale
            const scale = scaleStep ** dis;

            // rotateY
            const currentRotateY = rotateY * -sign;
            item.style.transform = `translateX(${xOffset}px) scale(${scale}) rotateX(${rotateX}deg) rotateY(${currentRotateY}deg)`;
            // opacity
            item.style.opacity = (opacityStep ** dis).toString();
            // z - index
            item.style.zIndex = (items.length - dis).toString();
        }
    }

    layout();

    const prev = document.querySelector('.prev');
    const next = document.querySelector('.next');

    prev.onclick = function () {
        index--;
        if (index < 0) {
            index = 0;
        }
        layout();
    };

    next.onclick = function () {
        index++;
        if (index > items.length - 1) {
            index = items.length - 1;
        }
        layout();
    };

    items.forEach((item, i) => {
        item.onclick = function () {
            index = i;
            layout();
        }
    });
})();
